package com.szjz.elasticsearch.eshelper.config;

import com.szjz.elasticsearch.eshelper.property.ESRestClientProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @author shibo
 * @desc 读取配置文件 生成ES高级客户端
 * @date 2020/5/30 周六
 */

@Slf4j
@Configuration
public class ESClientConfiguration {

    @Autowired
    private ESRestClientProperties esRestClientProperties;

    private HttpHost[] getHttpHosts() {
        ArrayList<HttpHost> hostList = new ArrayList<>();
        List<String> uris = esRestClientProperties.getUris();
        uris.forEach(uri -> {
            String[] split = uri.split(":");
            hostList.add(new HttpHost(split[1].substring(2), Integer.parseInt(split[2]), split[0]));
        });
        return hostList.toArray(new HttpHost[0]);
    }

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        // 免密
        if (StringUtils.isEmpty(esRestClientProperties.getUsername()) || StringUtils.isEmpty(esRestClientProperties.getPassword())) {
            log.info("【ES集群】 免密 httpHosts: {}", (Object) getHttpHosts());
            return new RestHighLevelClient(RestClient.builder(getHttpHosts()));
        }
        // 加密
        else {
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(esRestClientProperties.getUsername(), esRestClientProperties.getPassword()));
            RestClientBuilder restClientBuilder = RestClient.builder(getHttpHosts())
                    .setHttpClientConfigCallback(
                            httpAsyncClientBuilder -> httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
                    );
            log.info("【ES集群】 加密 httpHosts: {}", (Object) getHttpHosts());
            return new RestHighLevelClient(restClientBuilder);
        }
    }

}
